/*
 * @Author: Leng
 * @Date: 2021-02-01 14:54:32
 * @Description: 
 * @FilePath: \vue-leng\src\config\tool.js
 */

import Storage from '../utils/utilStorage'

const Tool = (function () {
    let tool = {
        ss: {
            storage: new Storage({ source: window.sessionStorage })
        },
        ls: {
            storage: new Storage({ source: window.localStorage })
        }
    }
    // 设置cookie值
    tool.setCookie = function (name, value, seconds) {
        var exdate = new Date()
        exdate.setTime(exdate.getTime() + seconds)
        document.cookie = name + '=' + encodeURI(value) +
            ((seconds == null) ? '' : ';expires=' + exdate.toGMTString())
    }
    // 获取cookies值
    tool.getCookie = function (name) {
        if (document.cookie.length > 0) {
            var start = document.cookie.indexOf(name + '=')
            if (start !== -1) {
                start = start + name.length + 1
                var end = document.cookie.indexOf(';', start)
                if (end === -1) end = document.cookie.length
                return decodeURI(document.cookie.substring(start, end))
            }
        }
        return ''
    }
    // 清楚本地cookie
    tool.clearCookie = function () {
        if (document.cookie.length > 0) {
            console.log('-----clearCookie', document.cookie)
            var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
            if (keys) {
                for (var i = keys.length; i--;)
                    document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
            }
        }
    }

    // 缓存值
    tool.ss.setItem = tool.ls.setItem = function (key, val, expired) {
        this.storage.setItem(key, val, expired)
    }
    // 获取值
    tool.ss.getItem = tool.ls.getItem = function (key) {
        return this.storage.getItem(key)
        //   return JSON.parse(this.storage.getItem(key))
        // } catch (err) {
        //   return null
        // }
    }
    // 删除缓存
    tool.ss.removeItem = tool.ls.removeItem = function (key) {
        this.storage.removeItem(key)
    }
    // 清除缓存
    tool.ss.clear = tool.ls.clear = function () {
        this.storage.clear()
    }
    tool.generateUUID = function () {
        var d = new Date().getTime()
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0
            d = Math.floor(d / 16)
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
        })
        return uuid
    }
    tool.isPC = function () {
        let userAgentInfo = navigator.userAgent;
        let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
        for (let v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                return false
            }
        }
        return true
    }
    /**
     * 判断当前设备
     * @returns {string}
     */
    tool.isIosOrAndroid = function () {
        let u = navigator.userAgent
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
        let isStr = ''
        if (isAndroid) {
            isStr = 'android'
        }
        if (isiOS) {
            isStr = 'ios'
        }
        return isStr
    }
    // 动态加载css，id参数用于标示唯一，非必需
    tool.loadCSS = function (url, id, className) {
        if (id) {
            let dom = document.getElementById(id)
            if (dom) {
                dom.href = url
                return
            }
        }
        let link = document.createElement('link')
        id && (link.id = id)
        className && (link.className = className)
        link.rel = 'stylesheet';
        link.type = 'text/css'
        link.href = url
        document.querySelector('head').appendChild(link)
    }
    // 动态加载js，id参数用于唯一标示，非必需
    tool.loadScript = function (url, callback, id, className) {
        if (id) {
            let dom = document.getElementById(id)
            if (dom) {
                let flag = false
                callback && callback(flag)
                return
            }
        }
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript')
        if (id) {
            script.setAttribute('id', id)
        }
        if (className) {
            script.setAttribute('class', className)
        }
        if (callback) {
            script.onload = script.onreadystatechange = function () {
                let flag = !this.readyState || this.readyState === 'loaded' || this.readyState === 'complete'
                callback(flag)
            };
            script.onerror = function (res) {
                let flag = false
                callback(flag)
            };
        }
        script.setAttribute('src', url)
        document.body.appendChild(script)
    }
    // 解决ios因软键盘弹出导致元素偏移的问题
    tool.fixInputLayout = function () {
        const isIphone = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        let keybordShow = false
        document.body.addEventListener('focusin', (e) => {
            keybordShow = true
            setTimeout(function () {
                fixLayout(e)
            }, 520)
        })
        document.body.addEventListener('focusout', () => {
            keybordShow = false
            setTimeout(function () {
                fixLayout()
            }, 100)
        })
        function fixLayout(e) {
            if (isIphone) {
                if (!keybordShow) {
                    window.scroll(document.body.scrollHeight, 0)
                    // document.body.scrollTop = document.body.scrollHeight
                    // document.body.scrollTop = 0;
                }
            } else {
                if (e && e.target.nodeName == 'INPUT') {
                    keybordShow && e.target.scrollIntoView(false)
                }
            }
        }
    }
    // 非pc模式不记载app工具js
    // if (!tool.isPC()) {
    //     tool.fixInputLayout()
    // }
    /**
     * @description: 加载iconfont
     */
    // 加载应用图标
    // tool.loadIconfont = () => {
    //     let iconUrl = $config.iconfont
    //     console.log(iconUrl, 666666)
    //     if(!iconUrl) return
    //     this.loadCss(iconUrl + '.css', null, 'leng-font-css')
    //     this.loadScript(iconUrl + '.js', null, 'leng-font-js')
    // }
    // // 销毁应用图标
    // tool.destructIconfont = () => {
    //     const fontJs = document.getElementById('leng-font-js')
    //     const fontCss = document.getElementById('leng-font-css')
    //     fontJs && fontJs.remove()
    //     fontCss && fontCss.remove()
    // }
    return tool
})()

window.$tool = Tool

export default Tool